#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include "stm32-spi.h"
#include "stm32-spi-tr700.h"
#include "otdrtestinterface.h"

int TR700_ls_on(DeviceInfo_t *dev, \
        int Lambda_nm, \
        float power_dBm, \
        int mod)
{
    struct tr700_setls_tx   lsparam;
    static int wave[10] = {0, 1310, 1550};
    int i, ch;

    ch = 0;
    for(i = 0; i < 6; i++){
        if(wave[i] == Lambda_nm){
            ch = i;
            break;
        }
    }
    if(ch == 0) return 1;

    lsparam.dbm  = power_dBm;
    lsparam.mode = mod;
    lsparam.ch   = ch;

    usleep(10000);
#if DATA_SPI
    stm_setls(dev->stm32dev, &lsparam);
#else
    printf("stm_setls on\n");
#endif
    usleep(10000);
    return 0;
}

int TR700_ls_off(DeviceInfo_t *dev)
{
    struct tr700_setls_tx lsparam;

    lsparam.dbm  = -10;
    lsparam.mode = 0;
    lsparam.ch   = 0;
    usleep(10000);
#if DATA_SPI
    stm_setls(dev->stm32dev, &lsparam);
#else
    printf("stm_setls off\n");
#endif
    usleep(10000);
    return 0;
}

static int stm_getopm_random(struct stm32_spi_dev *stm32dev, \
        struct tr700_getopm *opm_out)
{
    float dbm;
    int rn;

    getRandomLessThan(50, &rn, 1);
    dbm = (float)rn / 100;

    opm_out->wave = 1310;
    opm_out->dbm = -1-dbm;
    opm_out->mode = 0;
    return 0;
}

int TR700_opm_read(DeviceInfo_t *dev, \
        int Lambda_nm, \
        float refvalue_dBm, \
        float *power_mW, \
        float *power_dBm, \
        float *power_ref)
{
    struct tr700_getopm     opmparam;
    float vdbm, vmw, vref;

    usleep(10000);
#if DATA_SPI
    stm_getopm(dev->stm32dev, &opmparam);
#else
    stm_getopm_random(dev->stm32dev, &opmparam);
#endif
    usleep(10000);
    vdbm = opmparam.dbm;
    vmw = exp(0.2302585092994045684017991454684 * vdbm);
    if(fabs(refvalue_dBm) >= 70)    vref = 8192.0;
    else                            vref = vdbm - refvalue_dBm;

    if(power_mW != NULL)    *power_mW = vmw;
    if(power_dBm != NULL)    *power_dBm = vdbm;
    if(power_ref != NULL)    *power_ref = vref;

    return 0;
}

int TR700_opm_getRef(DeviceInfo_t *dev, \
        int Lambda_nm, \
        float *power_dBm)
{
    return TR700_opm_read(dev, Lambda_nm, 8192.0, NULL, power_dBm, NULL);
}

